$(function(){
	app.init();
});

var app = {
	adminPath: 'admin_express',
	init(){
		this.toggleAside();
		this.deleteConfirm();
		this.resizeIframe();
		this.changeStatus();
		this.changeNum();
	},
	deleteConfirm() {
		$('.delete').click(function() {
			var flag = confirm('您确定要删除吗？');
			return flag;
		});
	},
	resizeIframe() {
		let heights = document.documentElement.clientHeight - 100;
		let rightMainObj = document.getElementById('rightMain');
		if(rightMainObj){
			document.getElementById('rightMain').height = heights;
		}
	},
	toggleAside() {
		$('.aside h4').click(function() {
			$(this).siblings('ul').slideToggle();
		})
	},
	changeStatus(){
		let adminPath = this.adminPath;
		$('.chStatus').click(function() {
			let id = $(this).attr('data-id');
			let model = $(this).attr('data-model');
			let field = $(this).attr('data-field');
			let el = $(this);
			$.get('/'+adminPath+'/changeStatus', {id: id, model: model, field: field}, (response)=>{
				if(response.success){ //根据返回体修改img标签的src属性
					if(el.attr('src').indexOf('yes') != -1){
						el.attr('src', '/admin/images/no.png');
					}else{
						el.attr('src', '/admin/images/yes.png');
					}
				}
			})
		})
	},
	changeNum() {
		let adminPath = this.adminPath;
		$('.chSpanNum').click(function() {
			// 1.获取el中的值
			let spanNum = $(this).html().trim();
			let spanEl = $(this);
			// 2.创建一个input的dom节点
			// let input = $('<input vlaue="" style="width: 60px">');
			let input = $('<input value="">');
			$(input).css('width', spanNum.length*10+'px');
			// 3.把input放在el里
			$(this).html(input);
			// 4.让input获取焦点，给input赋值
			$(input).trigger('focus').val(spanNum);
			// 5.点击input的时候阻止冒泡
			$(input).click(function(e){
				e.stopPropagation();
			});
			// 6.鼠标离开时给span赋值，触发ajax请求
			$(input).blur(function(){
				let inputNum = $(this).val();
				if(inputNum.length > 0){
					spanEl.html(inputNum);
				}else{
					spanEl.html(0);
				}
				// 触发ajax请求
				let id = spanEl.attr('data-id');
				let model = spanEl.attr('data-model');
				let field = spanEl.attr('data-field');
				$.get('/'+adminPath+'/changeNum',{id: id, model: model, field: field, num: inputNum}, (response)=>{
					if(!response.success){
						console.log(response);
					}
				})
			});
		})
	}
}

$(window).resize(function() {
	app.resizeIframe();
})